<template>
    <div class="hw-editor" :style="`width: ${width}`">
        <toolbar style="border-bottom: 1px solid #ccc;"
                 :editor="editorRef"
                 :defaultConfig="toolbarConfig"
                 :mode="mode"></toolbar>
        <editor :style="`height: ${height}; overflow:hidden`" v-model="valueHtml"
                :defaultConfig="editorConfig"
                :mode="mode"
                @onCreated="handleCreated" @onChange="onChanges"></editor>
    </div>
</template>

<script>
import "@wangeditor/editor/dist/css/style.css";
import {Editor, Toolbar} from "@wangeditor/editor-for-vue";
import { onBeforeUnmount, onMounted, ref, shallowRef } from "vue";
import {uploadImageUrl} from "@/utils/request";
// import {ElMessageBox} from "element-plus";

export default {
    name: "veaEditorComponents",
    components: {Editor, Toolbar},
    props: {
        height: {
            default: () => "300px"
        },
        width: {
            default: () => "65%"
        },
        its: {
            default: () => ""
        }
    },
    setup(props,contentText) {
        // 编辑器实例，必须用 shallowRef
        const editorRef = shallowRef();

        // 内容 HTML
        const valueHtml = ref(props.its);

        // 模拟 ajax 异步获取内容
        onMounted(() => {
            setTimeout(() => {
                valueHtml.value = props.its;
            }, 1500);
        });

        const toolbarConfig = {};
        const editorConfig = {
            placeholder: "请输入内容...",
            MENU_CONF: {
                uploadImage: {
                    server: uploadImageUrl+"/image_upload?file_name=editor",
                    fieldName: "editor",
                    // 单个文件上传失败
                    onFailed(file, res) {
                        console.log(res)
                    },
                }
            }
        };

        const onChanges = () => {
            contentText.emit("editor", valueHtml);
        };

        // 组件销毁时，也及时销毁编辑器
        onBeforeUnmount(() => {
            const editor = editorRef.value;
            if (editor == null) return;
            editor.destroy();
        });

        const handleCreated = (editor) => {
            editorRef.value = editor; // 记录 editor 实例，重要！
        };

        return {
            editorRef,
            valueHtml,
            mode: "default", // 或 'simple'
            toolbarConfig,
            editorConfig,
            handleCreated,
            onChanges
        };
    }
};
</script>

<style lang="less" scoped>
.hw-editor {
    border: 1px solid #dedede;

    ///deep/ .hw-editor-info{
    //    height: 300px;
    //    overflow: hidden;
    //}
}
</style>
